import { useRequest } from '@umijs/hooks';
import { Button, Form, Input, message, Tree, TreeSelect } from 'antd';
import { Store } from 'rc-field-form/lib/interface';
import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import { getSecretString } from '../../../utils/encrypt';
import { fetchRequest } from '../../../utils/Request';
import { url } from '../../../utils/url';

const { TreeNode } = Tree;

export default function AddUser(props: any) {


    //获取redux中的数据
    const myData = useSelector((state: any) => {

        const data = state.deptManage.deptData
        disableSelect(data)
        return {
            deptData: data,
            authData: state.staffManage.roleTable.data
        }
    })


    //递归修改item的key
    function disableSelect(arr: any[],) {
        arr.map(item => {
            delete item.disabled
            item.key = item.deptID
            item.value = item.deptID
            if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
                return;
            } else {
                disableSelect(item.children)
            }
        })
    }

    const [form] = Form.useForm()

    const layout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 14 },
    };

    const tailLayout = {
        wrapperCol: { offset: 5, span: 14 },
    };


    //渲染
    const renderTreeNodes = (data: any) =>
        data.map((item: any) => {
            //   console.log(item);
            if (item.children) {
                // console.log(item);
                // console.log(this.state.relType);
                return (
                    <TreeNode
                        title={item.title}
                        key={item.key}
                        selectable={false}
                        // dataRef={item}
                        checked={true}
                        {...item}
                    // disableCheckbox={item.ref === 3}
                    >
                        {renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return (
                <TreeNode
                    //   disableCheckbox={item.ref === 3}
                    selectable={false}
                    //   disabled={item.ref === 3}
                    checked
                    key={item.key}
                    {...item}
                />
            );
        });


    function onFinish(value: Store) {

        const data: { "roleID": string; "authID": string; }[] = []
        value?.roleAuth?.map((item: string) => {
            const temp = item.split("-");
            if (temp.length > 1)
                data.push({ "roleID": temp[0], "authID": temp[1] })
        })

        const params = {
            ...value,
            phone: getSecretString(value.phone),
            pwd: getSecretString(value.pwd),
            roleAuth: data
        }

        addNewUser.run(params)


    }

    async function addNewUserRequest(params: any) {
        try {
            const json = await fetchRequest(url.MODIFY_USER_URL, params);
            if (json.success) {
                message.destroy();
                message.success("新增成功!");
                props.onAddSuccess();
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message);
        }
    }

    const addNewUser = useRequest(addNewUserRequest, {
        manual: true,
        loadingDelay: 200
    })
    const [value, setValue] = useState(undefined);
    const onChange = (value: any) => {
        setValue(value)

    }


    return (
        <Form form={form} {...layout} onFinish={onFinish}>
            <Form.Item label="用户名" name="userName" rules={[{ required: true, message: '必须要输入用户名' },
            {
                pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/,
                message: '用户名不符合规范'
            }, {
                max: 20,
                message: '用户名长度过长'
            }]}>
                <Input placeholder="请输入用户名" />
            </Form.Item>

            <Form.Item label="手机号" name="phone" rules={[{ required: true, message: '必须要输入手机号码' }, {
                pattern: /^1[3456789]\d{9}$/,
                message: '手机号码格式错误！'
            }]}>
                <Input placeholder="请输入手机号" />
            </Form.Item>

            <Form.Item label="密码" name="pwd" rules={[{
                required: true,
                message: '请输入密码!'
            }, {
                pattern: /^.*(?=.{8,16})(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%^&*?\(\)+=\[\]\{\}_<>,.;:'"-]).*$/,
                message: '密码必须包含数字，字母和特殊字符,至少为8位！'
            }]}>
                <Input.Password placeholder="请输入密码" />
            </Form.Item>

            <Form.Item label="管理部门" name="deptList" rules={[{ required: true, message: '必须要选择管理部门' }]}>
                <TreeSelect className="form-item"
                    treeData={myData.deptData}
                    multiple
                    maxTagCount={3}
                    showSearch={true}
                    treeNodeFilterProp={'title'}
                    allowClear
                    placeholder="请选择管理部门"
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    value={value}
                    onChange={onChange}
                />
            </Form.Item>

            <Form.Item label="权限选择" name="roleAuth" valuePropName="checkedKeys">
                <Tree checkable onCheck={handleChange}>{
                    renderTreeNodes(myData.authData)}</Tree>
            </Form.Item>

            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" loading={addNewUser.loading}>提交</Button>
            </Form.Item>
        </Form>
    )


    function handleChange(data: any) {
        form.setFieldsValue({ roleAuth: data })
    }
}
